package com.sanji.sjmallmodule.goods;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.sanji.sjmallapp.MallApplication;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallutils.JsonParseUtil;
import com.sanji.sjmallutils.Tools;
import com.umeng.analytics.MobclickAgent;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 搜索页
 */
public class SearchFragment extends Fragment implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, NoHttpListener {
    @BindView(R.id.search_smartphone_gride)
    GridView smartphoneGride;
    @BindView(R.id.search_tablet_gride)
    GridView tabletGride;
    @BindView(R.id.search_smart_life_gride)
    GridView smartLifeGride;
    @BindView(R.id.search_parts_gride)
    GridView partsGride;
    @BindView(R.id.search_m_store_gride)
    GridView mStoreGride;
    @BindView(R.id.search_type_radioGroup)
    RadioGroup typeRadioGroup;
    @BindView(R.id.fragment_search_img)
    ImageView fragmentSearchImg;
    @BindView(R.id.fragment_search_edit)
    EditText searchEdit;
    private String searchName;
    public static List<SearchTypeBean> smartphoneData;
    private List<SearchTypeBean> tabletsData;
    private List<SearchTypeBean> partsData;
    private List<SearchTypeBean> smartLifeData;
    private List<SearchTypeBean> mStoreData;
    private List<SearchTypeBean> allNoPartData;//所有除了配件以外的手机品牌
    private List<SearchTypeBean> partBrandData;//配件的品牌
    private SearchTypeAdapter smartphoneAdapter;
    private SearchTypeAdapter tabletsAdapter;
    private SearchTypeAdapter partsAdapter;
    private SearchTypeAdapter smartLifeAdapter;
    private SearchTypeAdapter mStoreAdapter;
    private Intent intent;
    private int index = 1;
    private View rootView;
    private Request<JSONObject> request;
    String url;
    private String phoneParam = "lj";//智能机
    private String lifeParam = "bxjx";//智能生活
    private String mStoreParam = "dz";//移动便利店
    private String tableParam = "pb";//平板
    private String partParam = "accessory";//配件
    private String allNoPartParam = "sj";//所有除配件以外的品牌
    private PopupWindow btnWindow;//手机、配件的popWindow
    TextView searchPartTv;
    TextView searchPhoneTv;
    private Boolean isPopShow;
    private String searchParam = "";//手机、配件的参数

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_search, null);
            ButterKnife.bind(this, rootView);
            initView();
        }
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    /**
     * 初始化数据
     */
    public void initView() {
        smartphoneData = new ArrayList<>();
        tabletsData = new ArrayList<>();
        partsData = new ArrayList<>();
        smartLifeData = new ArrayList<>();
        mStoreData = new ArrayList<>();
        allNoPartData = new ArrayList<>();
        partBrandData = new ArrayList<>();
        //默认选中第一个
        ((RadioButton) typeRadioGroup.getChildAt(0)).setChecked(true);
        itemSelectOnclick(1);
        typeRadioGroup.setOnCheckedChangeListener(this);
        fragmentSearchImg.setOnClickListener(this);
        requestTypeData(phoneParam);
        if (allNoPartData.size() == 0) {
            requestPartBrand();
        }
        searchEdit.setOnKeyListener(onkey);
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                return (keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
    }

    View.OnKeyListener onkey = new View.OnKeyListener() {
        @Override
        public boolean onKey(View view, int i, KeyEvent keyEvent) {
            if (i == keyEvent.KEYCODE_ENTER) {
                //弹出搜索框
                showBtnPop();
            }
            return false;
        }
    };

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.search_smartphone_radioBtn:
                //智能机
                smartphoneGride.setVisibility(View.VISIBLE);
                partsGride.setVisibility(View.GONE);
                mStoreGride.setVisibility(View.GONE);
                smartLifeGride.setVisibility(View.GONE);
                tabletGride.setVisibility(View.GONE);
                index = 1;
                if (smartphoneData.size() == 0) {
                    requestTypeData(phoneParam);
                }
                itemSelectOnclick(index);
                break;
            case R.id.search_tablet_radioBtn:
                //平板
                smartphoneGride.setVisibility(View.GONE);
                partsGride.setVisibility(View.GONE);
                mStoreGride.setVisibility(View.GONE);
                smartLifeGride.setVisibility(View.GONE);
                tabletGride.setVisibility(View.VISIBLE);
                index = 2;
                if (tabletsData.size() == 0) {
                    requestTypeData(tableParam);
                }
                itemSelectOnclick(index);
                break;
            case R.id.search_parts_radioBtn:
                //配件
                smartphoneGride.setVisibility(View.GONE);
                partsGride.setVisibility(View.VISIBLE);
                mStoreGride.setVisibility(View.GONE);
                smartLifeGride.setVisibility(View.GONE);
                tabletGride.setVisibility(View.GONE);
                index = 3;
                //先取数据
                partsData = MallApplication.getApplication().getPartList();
                if (partsData.size() == 0) {
                    requestTypeData(partParam);
                }
                if (null == partsAdapter) {
                    partsAdapter = new SearchTypeAdapter(getActivity(), partsData);
                    partsGride.setAdapter(partsAdapter);
                } else {
                    partsAdapter.notifyAdapter(partsData);
                }
                itemSelectOnclick(index);
                break;
            case R.id.search_smart_life_radioBtn:
                //智能生活
                smartphoneGride.setVisibility(View.GONE);
                partsGride.setVisibility(View.GONE);
                mStoreGride.setVisibility(View.GONE);
                smartLifeGride.setVisibility(View.VISIBLE);
                tabletGride.setVisibility(View.GONE);
                index = 4;
                if (smartLifeData.size() == 0) {
                    requestTypeData(lifeParam);
                }
                itemSelectOnclick(index);
                break;
            case R.id.search_m_store_radioBtn:
                //移动便利店
                smartphoneGride.setVisibility(View.GONE);
                partsGride.setVisibility(View.GONE);
                mStoreGride.setVisibility(View.VISIBLE);
                smartLifeGride.setVisibility(View.GONE);
                tabletGride.setVisibility(View.GONE);
                index = 5;
                if (mStoreData.size() == 0) {
                    requestTypeData(mStoreParam);
                }
                itemSelectOnclick(index);
                break;
        }
    }

    /**
     * 选择的点击事件
     */
    public void itemSelectOnclick(int index) {
        switch (index) {
            case 1:
                smartphoneGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        smartphoneAdapter.setSelection(i);
                        SearchTypeBean searchTypeBean = (SearchTypeBean) smartphoneAdapter.getItem(i);
                        intent = new Intent(getActivity(), SelectTypeActivity.class);
                        intent.putExtra("intentType", ConfigConts.MACHINE_PHONE);
                        intent.putExtra("searchName", searchTypeBean.getSearchTypeName());
                        intent.putExtra("brandIds", searchTypeBean.getId());
                        intent.putExtra("selectI", i);
                        smartphoneAdapter.notifyAdapter(smartphoneData);
                        startActivity(intent);
                    }
                });
                break;
            case 2:
                tabletGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        tabletsAdapter.setSelection(i);
                        tabletsAdapter.notifyAdapter(tabletsData);
                        SearchTypeBean searchTypeBean = (SearchTypeBean) tabletsAdapter.getItem(i);
                        intent = new Intent(getActivity(), SelectTypeActivity.class);
                        intent.putExtra("intentType", ConfigConts.MACHINE_TABLE);
                        intent.putExtra("searchName", searchTypeBean.getSearchTypeName());
                        intent.putExtra("brandIds", searchTypeBean.getId());
                        intent.putExtra("selectI", i);
                        startActivity(intent);
                    }
                });
                break;
            case 3:
                partsGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        SearchTypeBean searchTypeBean = (SearchTypeBean) partsAdapter.getItem(i);
                        partsAdapter.setSelection(i);
                        partsAdapter.notifyAdapter(partsData);
                        intent = new Intent(getActivity(), SelectTypeActivity.class);
                        intent.putExtra("intentType", ConfigConts.MACHINE_PARET);
                        intent.putExtra("catIds", searchTypeBean.getId());
                        intent.putExtra("searchName", searchTypeBean.getSearchTypeName());
                        intent.putExtra("selectI", i);
                        startActivity(intent);
                    }
                });
                break;
            case 4:
                smartLifeGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        SearchTypeBean searchTypeBean = (SearchTypeBean) smartLifeAdapter.getItem(i);
                        smartLifeAdapter.setSelection(i);
                        smartLifeAdapter.notifyAdapter(smartLifeData);
                        intent = new Intent(getActivity(), SelectTypeActivity.class);
                        intent.putExtra("intentType", ConfigConts.MACHINE_LIFE);
                        intent.putExtra("searchName", searchTypeBean.getSearchTypeName());
                        intent.putExtra("brandIds", searchTypeBean.getId());
                        intent.putExtra("selectI", i);
                        startActivity(intent);
                    }
                });
                break;
            case 5:
                mStoreGride.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        SearchTypeBean searchTypeBean = (SearchTypeBean) mStoreAdapter.getItem(i);
                        mStoreAdapter.setSelection(i);
                        mStoreAdapter.notifyAdapter(mStoreData);
                        intent = new Intent(getActivity(), SelectTypeActivity.class);
                        intent.putExtra("intentType", ConfigConts.MACHINE_STORE);
                        intent.putExtra("searchName", searchTypeBean.getSearchTypeName());
                        intent.putExtra("brandIds", searchTypeBean.getId());
                        intent.putExtra("selectI", i);
                        startActivity(intent);
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求数据类型
     */
    public void requestTypeData(String name) {
        url = ConfigAPI.GOODS_TYPE_URL + name;
        request = NoHttp.createJsonObjectRequest(url, RequestMethod.GET);
        request.setCancelSign(url.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), url.hashCode(), request, this, true, true);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_search_img:
                //弹出来一个选择框
                showBtnPop();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != request) {
            request.cancel();
        }
    }

    @Override
    public void onSuccessed(int what, Response response) {
        JSONObject json = (JSONObject) response.get();
        String status = json.optString(ConfigConts.STATUS_STRING);
        if (what == url.hashCode()) {
            if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                JSONArray array = json.optJSONArray("result");
                List<SearchTypeBean> mData = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    try {
                        JSONObject object = (JSONObject) array.get(i);
                        String name = object.optString("NAME");
                        String id = object.optString("ID");
                        SearchTypeBean bean = new SearchTypeBean(name, id, 0);
                        mData.add(bean);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                switch (index) {
                    case 1:
                        smartphoneData.clear();
                        smartphoneData.addAll(mData);
                        if (null == smartphoneAdapter) {
                            smartphoneAdapter = new SearchTypeAdapter(getActivity(), smartphoneData);
                            smartphoneGride.setAdapter(smartphoneAdapter);
                        } else {
                            smartphoneAdapter.notifyAdapter(smartphoneData);
                        }
                        MallApplication.getApplication().setPhoneList(smartphoneData);
                        break;
                    case 2:
                        tabletsData.clear();
                        tabletsData.addAll(mData);
                        if (null == tabletsAdapter) {
                            tabletsAdapter = new SearchTypeAdapter(getActivity(), tabletsData);
                            tabletGride.setAdapter(tabletsAdapter);
                        } else {
                            tabletsAdapter.notifyAdapter(tabletsData);
                        }
                        MallApplication.getApplication().setTableList(tabletsData);
                        break;
                    case 3:
                        partsData.clear();
                        partsData.addAll(mData);
                        if (null == partsAdapter) {
                            partsAdapter = new SearchTypeAdapter(getActivity(), partsData);
                            partsGride.setAdapter(partsAdapter);
                        } else {
                            partsAdapter.notifyAdapter(partsData);
                        }
                        MallApplication.getApplication().setPartList(partsData);
                        break;
                    case 4:
                        smartLifeData.clear();
                        smartLifeData.addAll(mData);
                        if (null == smartLifeAdapter) {
                            smartLifeAdapter = new SearchTypeAdapter(getActivity(), smartLifeData);
                            smartLifeGride.setAdapter(smartLifeAdapter);
                        } else {
                            smartLifeAdapter.notifyAdapter(smartLifeData);
                        }
                        MallApplication.getApplication().setLifeList(smartLifeData);
                        break;
                    case 5:
                        mStoreData.clear();
                        mStoreData.addAll(mData);
                        if (null == mStoreAdapter) {
                            mStoreAdapter = new SearchTypeAdapter(getActivity(), mStoreData);
                            mStoreGride.setAdapter(mStoreAdapter);
                        } else {
                            mStoreAdapter.notifyAdapter(mStoreData);
                        }
                        MallApplication.getApplication().setSmartStoreList(mStoreData);
                        break;
                }

            } else {
                String errorMsg = json.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(getActivity(), errorMsg);
            }
        }
        if (what == ConfigAPI.GOODS_PART_BRAND_URL.hashCode()) {
            if (status.equals(ConfigConts.STATUS_SUCCESS)) {
                //
                JSONObject object = json.optJSONObject("result");
                JSONArray sjBrandArry = object.optJSONArray("sjBrand");
                JSONArray accessoryTypeArry = object.optJSONArray("accessoryType");
                JSONArray accessoryBrandArry = object.optJSONArray("accessoryBrand");

                allNoPartData.addAll(JsonParseUtil.goodsBrandParse(sjBrandArry, 0));


                //配件的类型
                partsData.addAll(JsonParseUtil.goodsBrandParse(accessoryTypeArry, 0));


                //配件的品牌
                partBrandData.addAll(JsonParseUtil.goodsBrandParse(accessoryBrandArry, 0));

                MallApplication.getApplication().setPartBrandList(partBrandData);
                MallApplication.getApplication().setPartList(partsData);
                MallApplication.getApplication().setAllNoParetList(allNoPartData);
            } else {
                String errorMsg = json.optString(ConfigConts.ERRORMSG);
                Tools.toastTools(getActivity(), errorMsg);
            }
        }
    }

    @Override
    public void onFailed(int what, Response response) {
        Tools.toastTools(getActivity(), "连接超时！");
    }

    /**
     * 弹出搜手机、配件的popWindow
     */
    public void showBtnPop() {
        if (null == btnWindow) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.popwindow_phone_part, null);
            searchPartTv = (TextView) view.findViewById(R.id.search_part);
            searchPhoneTv = (TextView) view.findViewById(R.id.search_phone);
            btnWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            //实例化一个colorDraable颜色为透明色
            ColorDrawable dw = new ColorDrawable(0xb0000000);
            btnWindow.setBackgroundDrawable(dw);
            btnWindow.setFocusable(true);
        }
        btnWindow.showAsDropDown(searchEdit);
        isPopShow = true;
        setPopupViews(isPopShow, fragmentSearchImg);
        searchPartTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnWindow.dismiss();
                isPopShow = false;
                setPopupViews(isPopShow, fragmentSearchImg);
                searchParam = "";
                searchName = searchEdit.getText().toString();
                Intent intent = new Intent(getActivity(), SelectTypeActivity.class);
                intent.putExtra("intentType", ConfigConts.MULTIPLE_PART);
                if (TextUtils.isEmpty(searchName)) {
                    Tools.toastTools(getActivity(), getString(R.string.search_content));
                } else {
                    intent.putExtra("selectParam", searchName);
                    startActivity(intent);
                }
            }
        });
        searchPhoneTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btnWindow.dismiss();
                isPopShow = false;
                setPopupViews(isPopShow, fragmentSearchImg);
                searchParam = "";
                searchName = searchEdit.getText().toString().trim();
                Intent intent = new Intent(getActivity(), SelectTypeActivity.class);
                intent.putExtra("intentType", ConfigConts.MULTIPLE_PHONE);
                if (TextUtils.isEmpty(searchName)) {
                    Tools.toastTools(getActivity(), getString(R.string.search_content));
                } else {
                    intent.putExtra("selectParam", searchName);
                    startActivity(intent);
                }
            }
        });
        btnWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isPopShow = false;
                setPopupViews(isPopShow, fragmentSearchImg);
            }
        });
    }

    /**
     * 修改popup相应的指示布局
     */
    private void setPopupViews(boolean flag, ImageView imageView) {
        if (flag) {
            imageView.setImageResource(R.mipmap.select_down);
        } else {
            imageView.setImageResource(R.mipmap.search_imag);
        }
    }

    /**
     * 请求配件和除配件的手机品牌
     */
    public void requestPartBrand() {
        request = NoHttp.createJsonObjectRequest(ConfigAPI.GOODS_PART_BRAND_URL, RequestMethod.GET);
        request.cancelBySign(ConfigAPI.GOODS_PART_BRAND_URL.hashCode());
        NoHttpCallBack.getInstance().add(getActivity(), ConfigAPI.GOODS_PART_BRAND_URL.hashCode(), request, this, true, true);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SearchFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SearchFragment");
    }
}
